import json
import copy
import time
from copy import deepcopy
from flask import Blueprint, request, jsonify
from controllers.common import *
from controllers.db import *
import logging
import pandas as pd
import requests

al_pay_gift_project_api = Blueprint('al_pay_gift_project_api', __name__)
al_pay_gift_project_down_api = Blueprint('al_pay_gift_project_down_api', __name__)

USE_CMD_LOG = True

def al_pay_gift_log(module_name, host, info):
    if USE_CMD_LOG is False:
        return
    print(f'[Al_pay_gift] [{fomat_timestamp(int(time.time()))}] [Log] [{module_name}] host={host} - {info}', flush=True)


@al_pay_gift_project_api.route('/al_pay_gift_project', methods=['POST'])
def al_pay_gift_project():
    params = json.loads(request.data)

    # host = request.host
    print(request.headers, flush=True)
    if 'X-Forwarded-For' in request.headers:
        host = request.headers['X-Forwarded-For']
    else:
        host = request.host

    _action = params['action']
    _project = params['project']
    result_data = {'status': 200, 'data': {'msg': '', 'ret': 0, 'type': 'success', 'env': EVN, 'item': ''}}
    if _action == 'view':
        al_pay_gift_log('project', host, f'view project list')

        query = AlPayGiftProject.query.order_by('project').all()
        result = []
        for q in query:
            tmp = {
                "project": int(q.project),
                'remark': q.remark
            }
            result.append(tmp)
        result_data['data']['item'] = result
    elif _action == 'detail':
        al_pay_gift_log('project', host, f'view project detail project={_project}')
        query = AlPayGiftProject.query.filter_by(project=_project).first()
        tmp = {
            "project": int(query.project),
            'basic': json.loads(query.basic),
            'reward': json.loads(query.reward)
        }
        result_data['data']['item'] = tmp
    elif _action == 'update_part':
        _data = params['data']
        _part = params['part']

        al_pay_gift_log('project', host, f'update part project={_project}, part={_part}')

        if _part == 'basic':
            AlPayGiftProject.query.filter_by(project=_project).update({
                'basic': json.dumps(_data)
            })
        elif _part == 'gift_0':
            project_data = AlPayGiftProject.query.filter_by(project=_project).first()
            reward = json.loads(project_data.reward)
            reward['gift_0'] = _data
            project_data.reward = json.dumps(reward)
        elif _part == 'gift_1':
            project_data = AlPayGiftProject.query.filter_by(project=_project).first()
            reward = json.loads(project_data.reward)
            reward['gift_1'] = _data
            project_data.reward = json.dumps(reward)
        elif _part == 'gift_2':
            project_data = AlPayGiftProject.query.filter_by(project=_project).first()
            reward = json.loads(project_data.reward)
            reward['gift_2'] = _data
            project_data.reward = json.dumps(reward)
        db.session.commit()
        result_data['data']['msg'] = "更新成功"
    elif _action == 'remark':
        al_pay_gift_log('project', host, f'remark project={_project}')

        newRemark = params['remark']
        AlPayGiftProject.query.filter_by(project=_project).update({'remark': newRemark})
        db.session.commit()
        result_data['data']['msg'] = "Remark 更新成功"
    elif _action == 'clone':
        al_pay_gift_log('project', host, f'clone from={_project}')

        project_data = AlPayGiftProject.query.filter_by(project=_project).first()

        new_project_data = AlPayGiftProject(
            remark=project_data.remark,
            basic=project_data.basic,
            reward=project_data.reward,
        )
        db.session.add(new_project_data)
        db.session.commit()
        new_project_id = new_project_data.project
        if new_project_id is None:
            result_data['status'] = 500
            result_data['data']['msg'] = "克隆失败：id is None"
        else:
            al_pay_gift_log('project', host, f'clone to={new_project_id}')
            result_data['data']['msg'] = "克隆成功"
    elif _action == 'delete':
        al_pay_gift_log('project', host, f'delete project={_project}')

        project_data = AlPayGiftProject.query.filter_by(project=_project).first()
        db.session.delete(project_data)
        db.session.commit()
        project_data = AlPayGiftProject.query.filter_by(project=_project).first()
        if project_data is not None:
            result_data['status'] = 500
            result_data['data']['msg'] = "删除失败：id is not None"
        else:
            result_data['data']['msg'] = "删除成功"

    elif _action == 'stage_list':
        # 20230518 优化 时代动态读取
        stage_list = [{'label': '-1 - 全部时代', 'value': -1}]
        used_stage = []
        with open(GLOBAL_PATH + 'dynamic_sub_game.json', encoding='utf-8') as f:
            content = json.load(f)
        troop_control = content['open_control']['troop_control']
        default, special = troop_control['default'], troop_control['special']
        for stage in default:
            if stage not in used_stage:
                tmp = {'label': f'{stage} - 时代{stage+1}', 'value': stage}
                stage_list.append(tmp)
                used_stage.append(stage)

        for s_node in special:
            for stage in s_node['open']:
                if stage not in used_stage:
                    tmp = {'label': f'{stage} - 时代{stage+1}', 'value': stage}
                    stage_list.append(tmp)
                    used_stage.append(stage)

        result_data['data']['stage_list'] = stage_list

    return jsonify(result_data)


@al_pay_gift_project_down_api.route('/al_pay_gift_project_down/<int:is_push>', methods=['GET', 'POST'])
def al_pay_gift_project_down(is_push):
    # 20230518 优化 时代动态读取
    def get_total_stages():
        result = []
        with open(GLOBAL_PATH + 'dynamic_sub_game.json', encoding='utf-8') as f:
            content = json.load(f)
        troop_control = content['open_control']['troop_control']
        default, special = troop_control['default'], troop_control['special']
        for stage in default:
            if stage not in result:
                result.append(stage)

        for s_node in special:
            for stage in s_node['open']:
                if stage not in result:
                    result.append(stage)
        return result

    host = request.host

    al_pay_gift_log('project_download', host, f'is_push={is_push}')

    al_pay_gift_project = {}

    query = AlPayGiftProject.query.order_by('project').all()

    total_stages = get_total_stages()

    for q in query:
        project = int(q.project)
        basic = json.loads(q.basic)
        reward = json.loads(q.reward)

        gift_info = {}
        gift_index = 0
        for i in reward['gift_0']:
            gift_index = gift_index + 1
            stage = i['stage']
            stage.sort()
            if -1 in stage:
                stage = total_stages
            gift_info[str(gift_index)] = {
                'cost': RewardToTMysqlNew(i['cost']),
                'reward': RewardToTMysqlNew(i['reward']),
                'send_limit': i['send_limit'],
                'stage': stage,
                'level': 0
            }
        for i in reward['gift_1']:
            gift_index = gift_index + 1
            stage = i['stage']
            stage.sort()
            if -1 in stage:
                stage = total_stages
            gift_info[str(gift_index)] = {
                'cost': RewardToTMysqlNew(i['cost']),
                'reward': RewardToTMysqlNew(i['reward']),
                'send_limit': i['send_limit'],
                'stage': stage,
                'level': 1
            }
        for i in reward['gift_2']:
            gift_index = gift_index + 1
            stage = i['stage']
            stage.sort()
            if -1 in stage:
                stage = total_stages
            gift_info[str(gift_index)] = {
                'cost': RewardToTMysqlNew(i['cost']),
                'reward': RewardToTMysqlNew(i['reward']),
                'send_limit': i['send_limit'],
                'stage': stage,
                'level': 2
            }
        # 20221128优化 event_ui生成固定值 不在页面展示
        al_pay_gift_project[str(project)] = {
            'basic': {
                'event_ui': 0
            },
            'localization_doc': {
                'title': basic['doc_id'],
                'info': basic['doc_id'],
                'content': basic['doc_id']
            },
            'gift_info': gift_info,
            'extern0': {
                'recv_gift_num_limit': basic['recv_gift_num_limit']
            },
            'remark': q.remark
        }
    if is_push == 0:
        response = DownLoad('al_pay_gift_project', al_pay_gift_project, 0)
    if is_push == 1:
        r1 = DownLoad('al_pay_gift_project', al_pay_gift_project, 1)
        if r1:
            return jsonify({"msg": "发布成功", "ret": 1})
        else:
            return False
    return response
